<!-- 线索管理的编辑 -->
<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <div class="content">
          <NSpace>
            <NForm
              ref="formRef"
              :model="formValue"
              :rules="rules"
              require-mark-placement="left"
              label-placement="left"
              :label-width="115"
              label-align="right"
            >
              <NSpace>
                <NFormItem
                  label="线索名称:"
                  path="clueName"
                >
                  <NInput
                    v-model:value="formValue.clueName"
                    placeholder="藏家-征集方式-版本类型-征集数量"
                    style="width: 350px"
                  />
                </NFormItem>
                <NFormItem
                  label="线索状态:"
                  path="statusCode"
                >
                  <NSelect
                    :options="listOption"
                    v-model:value="formValue.statusCode"
                    placeholder="请选择线索状态"
                    clearable
                    style="width: 350px"
                    filterable
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="藏家"
                  path="collectorId"
                >
                  <NSelect
                    :options="listNameOption"
                    :value="formValue.collectorId"
                    @update:value="handleUpdateCollectorId"
                    placeholder="藏家"
                    style="width: 350px"
                    filterable
                  />
                </NFormItem>
                <NFormItem
                  label="联系方式:"
                  path="concatUser"
                >
                  <NSelect
                    :value="formValue.concatUser"
                    @update:value="handleUpdateConcatUser"
                    placeholder="请选择联系人"
                    :options="info?.transferList as any"
                    value-field="transferName"
                    label-field="transferName"
                    style="width: 175px"
                  />
                </NFormItem>
                <NFormItem
                  label=""
                  path="concatUserPhone"
                  :label-width="10"
                >
                  <NInput
                    v-model:value="formValue.concatUserPhone"
                    placeholder="输入联系方式"
                    style="width: 165px"
                    disabled
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="线索提供时间:"
                  path="provideTime"
                >
                  <NDatePicker
                    input-readonly
                    v-model:formatted-value="formValue.provideTime"
                    value-fxormat="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    default-time="00:00:00"
                    style="width: 350px"
                    placeholder="输入线索提供时间"
                  />
                </NFormItem>
                <NFormItem
                  label="线索提供方式:"
                  path="provideType"
                >
                  <NInput
                    v-model:value="formValue.provideType"
                    placeholder="输入线索提供方式"
                    style="width: 350px"
                  />
                </NFormItem>
              </NSpace>
              <NFormItem
                label="征集部对接人:"
                path="scopeOrPeopleList"
              >
                <div style="width: 100%">
                  <NButton
                    style="width: 130px; margin-bottom: 10rem"
                    type="primary"
                    ghost
                    @click="openScope"
                  >
                    选择对接人
                  </NButton>
                  <div
                    style="width: 370rem; background-color: #e1e1e1; padding: 10rem 0 8rem"
                    v-if="formValue.scopeOrPeopleList?.length"
                  >
                    <NScrollbar style="max-height: 120rem">
                      <div class="scope">
                        <div
                          class="userBox"
                          v-for="(item, index) in formValue.scopeOrPeopleList"
                          :key="index"
                        >
                          <div>{{ item.typeName }}</div>
                          <n-icon
                            @click="handleScope(item.identifyingId)"
                            style="cursor: pointer"
                          >
                            <CloseFilled />
                          </n-icon>
                        </div>
                      </div>
                    </NScrollbar>
                  </div>
                </div>
              </NFormItem>
              <NFormItem
                label="版本详情:"
                path="versionDetails"
              >
                <NInput
                  v-model:value="formValue.versionDetails"
                  type="textarea"
                  placeholder="输入版本详情"
                  style="width: 100%"
                />
              </NFormItem>
              <NFormItem
                label="线索反馈:"
                path="feedback"
              >
                <NInput
                  v-model:value="formValue.feedback"
                  type="textarea"
                  placeholder="输入线索反馈"
                  style="width: 100%"
                />
              </NFormItem>
            </NForm>
          </NSpace>
        </div>
      </NScrollbar>
    </div>
  </div>
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
    @close="modalVisible = false"
  >
    <VScope
      @close="modalVisible = false"
      @scopeSubmit="getScopeList"
      :defaultList="scopeList"
      :flat="true"
    />
  </NModal>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="confirm"
        :disabled="loading"
        :loading="loading"
      >
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  useMessage,
  NDatePicker,
  NModal,
  NIcon
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import { keysOf } from '@/utils/object'
import { format } from 'date-fns'
import VScope from '@/views/OA/Common/Scope.vue'
import { CloseFilled } from '@vicons/material'
import useRouteParam from '@/hooks/useRouteParam'

interface FormData {
  id: number
  userName: string | null
  collectTypeCode: string | null
  collectTypeCodeArr: string[] | null
  collectorTags: string | null
  collectorTypeCode: string | null
  idNo: string | null
  idType: string | null
  scopeOrPeopleList: Contact[] | null
  phone: string | null
  regionCode: string | null
  regionCodeCity: string | null
  regionCodeProvince: string | null
  remark: string | null
  transferList: TransferPerson[] | null
}

interface InfoModel extends FormData {
  id: number
  createdBy: string
  createdTime: string
  delFlag: number
  collectorTypeName: string
  collectTypeName: string
  collectorFlag: number
  donateNum: number
  idTypeName: string
  regionName: string
  sourceCode: string
  sourceName: string
}

interface TransferPerson {
  transferName: string | null
  transferPhone: string | null
}

interface Contact {
  identifyingId: string
  typeName: string
  parentId: string
  typeCode: string
  deptId: string
  fullId: string
}

// 获取藏家详情
const info = ref<InfoModel | null>(null)
const queryInfo = async (id: string) => {
  try {
    const [error, res] = await sendRequest<HttpResponse<InfoModel>>({
      module: 'collector',
      api: 'info',
      uri: {
        id
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    info.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const handleUpdateConcatUser = (value: string, option: any) => {
  formValue.concatUser = value
  formValue.concatUserPhone = option.transferPhone
}

const handleUpdateCollectorId = (value: string) => {
  formValue.collectorId = value as any
  formValue.concatUser = null
  formValue.concatUserPhone = null
  info.value = null
  queryInfo(value)
}

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const listOption = ref([])
const listNameOption = ref<any>([])
const formValue = reactive({
  clueName: '',
  statusCode: null,
  collectorId: null,
  concatUser: '',
  concatUserPhone: '',
  provideType: '',
  scopeOrPeopleList: [],
  versionDetails: '',
  feedback: '',
  receiveUser: '',
  provideTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss')
})
const rules = ref({
  clueName: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (!value || value.length == 0) return new Error('请输入线索名称')

      if (value.length > 100) return new Error('线索名称字数不得超过100')
      return true
    }
  },
  statusCode: {
    required: true,
    message: '请选择线索状态',
    trigger: ['change', 'blur']
  },
  collectorId: {
    required: true,
    message: '请选择藏家',
    trigger: ['change', 'blur']
  },
  concatUser: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value && value.length > 20) return new Error('联系人字数不得超过20')
      return true
    }
  },
  concatUserPhone: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value && value.length > 20) return new Error('联系方式字数不得超过20')
      return true
    }
  },
  provideType: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入线索提供方式')
      if (value && value.length > 100) return new Error('线索提供方式字数不得超过100')
      return true
    }
  },
  scopeOrPeopleList: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value && value.length > 20) return new Error('征集部对接人字数不得超过20')
      return true
    }
  },
  versionDetails: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value && value.length > 1000) return new Error('版本详情字数不得超过1000')
      return true
    }
  },
  feedback: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value && value.length > 1000) return new Error('线索反馈字数不得超过1000')
      return true
    }
  },
  provideTime: {
    required: true,
    message: '请选择线索提供时间',
    trigger: ['change', 'blur']
  }
})
// const provideTime = computed<any>({
//   get() {
//     return formValue.provideTime
//   },
//   set(v) {
//     formValue.provideTime = v
//   }
// })
// 打开发布范围
const modalVisible = ref(false)
const scopeList = ref()
const openScope = () => {
  scopeList.value = formValue.scopeOrPeopleList
  modalVisible.value = true
}
// 发布范围选择
const getScopeList = (v: any) => {
  formValue.scopeOrPeopleList = v
  modalVisible.value = false
}
// 范围选择是删除
const handleScope = (id: any) => {
  const index = formValue.scopeOrPeopleList?.findIndex((it: any) => it.identifyingId == id)
  formValue.scopeOrPeopleList?.splice(index, 1)
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
//征集信息-线索下拉
const getFunction = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A62'
      }
    }
  })
  if (error) return message.error(error.message)
  listOption.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
}
const listU = ref<any>([])
//藏家姓名下拉
const getNameFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'controllerOptions'
  })
  if (error) return message.error(error.message)
  listNameOption.value = res.data
  listU.value = res.data
}

//新增
const confirm = async () => {
  const validate = await Promise.all([
    new Promise((resolve, reject) => {
      formRef.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])
  if (!validate.every(Boolean)) return
  loading.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'updateNew',
    override: {
      data: {
        id: route.params.id,
        ...formValue
        // scopeOrPeopleList: formValue.scopeOrPeopleList?.map(it=>it.identifyingId).join(',')
      }
    }
  })
  loading.value = false
  if (error) return message.error(error.message)
  message.success(res.msg)
  goBack()
}
const getInfo = async () => {
  await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'infoManage',
    uri: {
      id: route.params.id
    }
  }).then(([err, res]) => {
    if (err) return
    if (res.data.collectorId) {
      queryInfo(res.data.collectorId)
    }
    keysOf(formValue).forEach((e) => {
      {
        // @ts-ignore
        formValue[e] = res.data[e] as never
      }
    })
  })
}
useRouteParam('id', () => {
  if (route.params.id) getInfo()
})
onMounted(() => {
  getFunction()
  getNameFunction()
  getInfo()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 168rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      .scope {
        display: grid;
        grid-template-columns: repeat(2, auto);
        gap: 10rem 0;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 170rem;
          height: 40rem;
          margin-left: 7rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          // margin-bottom: 10rem;
        }
      }
      .tableT {
        position: absolute;
        top: 38px;
        z-index: 888;
        background-color: #fff;
        width: 350px;

        .tr {
          height: 30px;
          margin: 0 10px;
          cursor: pointer;
          &:hover {
            background-color: #ebeceb;
          }

          .td {
            padding: 0 10px;
          }
        }
      }

      // .scope {
      //   width: 360rem;
      //   height: 130rem;
      //   background: #e1e1e1;
      //   margin-bottom: 25rem;
      // }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-base-selection-tags) {
  flex-wrap: nowrap;
  overflow: hidden;
  .n-base-clear {
    display: none;
  }
}
</style>
